package com.sikao.app.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sikao.app.R;
import com.sikao.app.adapter.InspectionReportAdapter;
import com.sikao.app.adapter.ProductExtraInfAdapter;
import com.sikao.app.bean.AddCollectBean;
import com.sikao.app.bean.AddCollectSubmitBean;
import com.sikao.app.bean.CancelCollectBean;
import com.sikao.app.bean.CancelCollectSubmitBean;
import com.sikao.app.bean.CheckCollectBean;
import com.sikao.app.bean.CheckCollectSubmitBean;
import com.sikao.app.bean.MallGoodsDetailBean;
import com.sikao.app.bean.ProductIndexBean;
import com.sikao.app.bean.ProductIndexListBeans;
import com.sikao.app.dao.AddCollectModel;
import com.sikao.app.dao.CancelCollectModel;
import com.sikao.app.dao.CheckCollectModel;
import com.sikao.app.dao.MallGoodsDetailModel;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.ui.base.BaseActivity;
import com.sikao.app.utils.ConstantClass;
import com.sikao.app.utils.JSONUtil;
import com.sikao.app.view.CountDownLinearLayout;
import com.sikao.app.view.MyGridView;
import com.sikao.app.view.MyListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 商城商品详情
 */
public class MallDetailsActivity extends BaseActivity implements View.OnClickListener {

	private TextView titleTv;
	private ImageView backIv;
	private MyListView productIndexListView;
	private MyGridView inspectionReportGridView;
	private RelativeLayout rl_ladder_price;

	private TextView tvGoodsName;
	private TextView tvGoodsPrice;
	private TextView tvViewTimes;
	private TextView tvAddTime;
	private TextView tvPayMethod;
	private TextView tvProductCode;
	private TextView tvIsPorted;//是否可拆分
	private TextView tvDeliveryArea;
	private TextView tvDeliveryType;
	private TextView tvCatName;
	private TextView tvNumber;
	private TextView tvNumberUnit;

	/*private TextView releaseTypeTv;//挂单方式
	private TextView canSplitTv;//是否可拆分标签*/

	//收藏按钮
	private Button bt_mall_collect;
	private Button orderBtn;
	//倒计时控件
	private CountDownLinearLayout countDownLinearLayout;

	private String goodsId = "0";
	private List<MallGoodsDetailBean.ResBean.StepPriceBean> step_price;//阶梯价格
	private MallGoodsDetailModel mallGoodsDetailModel;
	private MallGoodsDetailBean mallGoodsDetailBean;
	private ProductExtraInfAdapter productExtraInfAdapter;
	private InspectionReportAdapter inspectionReportAdapter;

	//产品指标
	private List<ProductIndexBean> productIndexBeanList = new ArrayList<ProductIndexBean>();
	private List<ProductIndexListBeans> productIndexListBeanses = new ArrayList<>();
	//质检报告
	private List<MallGoodsDetailBean.ResBean.CheckReportInfoBean> check_report = new ArrayList<>();
	//是否收藏
	private boolean isCollected = false;
	//收藏的id
	private String collectId = "0";
	public static MallDetailsActivity mallDetailsActivity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_mall_detail);
		super.onCreate(savedInstanceState);
		mallDetailsActivity = this;

	}

	@Override
	protected void initData() {
		goodsId = getIntent().getStringExtra("goodsId");
		//测试 临时注销 goodsId = 801+"";
		//Toast.makeText(this, " goodsId=" + goodsId, Toast.LENGTH_SHORT).show();
	}


	private void showLadderPrice(List<MallGoodsDetailBean.ResBean.StepPriceBean> stepPrice) {
		//    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		//    设置Title的图标
		//	builder.setIcon(R.drawable.iconfont_laba);
		//    设置Title的内容
		builder.setTitle("阶梯价格");
		//    设置Content来显示一个信息
		String content = "";
		if (stepPrice != null && stepPrice.size() > 0) {
			for (int i = 0; i < stepPrice.size(); i++) {
				content += stepPrice.get(i).getNumber() + "吨以上，" + stepPrice.get(i).getPrice() + "元/吨<br>";
			}
		} else {
			content = "此商品无阶梯价格";
		}

		builder.setMessage(Html.fromHtml(content));
		//    设置一个PositiveButton

		builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});

		//    显示出该对话框
		AlertDialog dialog = builder.create();
		dialog.setOnShowListener(new DialogInterface.OnShowListener() {
			private Button positiveBtn;

			@Override
			public void onShow(DialogInterface dialog) {

				positiveBtn = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
				positiveBtn.setTextColor(Color.BLUE);
			}
		});
		dialog.show();
	}

	@Override
	protected void initView() {
		titleTv = (TextView) findViewById(R.id.title_middle_tv);
		backIv = (ImageView) findViewById(R.id.title_left_img);
		productIndexListView = (MyListView) findViewById(R.id.listview_attrs);
		inspectionReportGridView = (MyGridView) findViewById(R.id.gridView1);
		orderBtn = (Button) findViewById(R.id.order_btn);
		rl_ladder_price = (RelativeLayout) findViewById(R.id.rl_step_price);

		tvGoodsName = (TextView) findViewById(R.id.tv_goods_name);
		tvGoodsPrice = (TextView) findViewById(R.id.tv_goods_price);
		tvViewTimes = (TextView) findViewById(R.id.tv_view_times);
		tvAddTime = (TextView) findViewById(R.id.tv_add_time);
		tvPayMethod = (TextView) findViewById(R.id.tv_pay_method);
		tvNumber = (TextView) findViewById(R.id.tv_number);
		tvNumberUnit = (TextView) findViewById(R.id.tv_number_unit);
		tvProductCode = (TextView) findViewById(R.id.tv_product_code);
		tvIsPorted = (TextView) findViewById(R.id.tv_is_ported);
		tvDeliveryArea = (TextView) findViewById(R.id.tv_delivery_area);
		tvDeliveryType = (TextView) findViewById(R.id.tv_delivery_type);
		tvCatName = (TextView) findViewById(R.id.tv_cat_name);
		countDownLinearLayout = (CountDownLinearLayout) findViewById(R.id.cdll);
		bt_mall_collect = (Button) findViewById(R.id.bt_mall_collect);

		//releaseTypeTv = (TextView) findViewById(R.id.release_type_tv);
		//canSplitTv = (TextView) findViewById(R.id.can_split_tv);
	}

	@Override
	protected void initListener() {
		backIv.setOnClickListener(this);
		orderBtn.setOnClickListener(this);
		rl_ladder_price.setOnClickListener(this);
		bt_mall_collect.setOnClickListener(this);
	}

	@Override
	protected void init() {
		titleTv.setText("商品详情");
		backIv.setVisibility(View.VISIBLE);

		productExtraInfAdapter = new ProductExtraInfAdapter(this, productIndexListBeanses);
		productIndexListView.setAdapter(productExtraInfAdapter);
		inspectionReportAdapter = new InspectionReportAdapter(this, check_report);
		inspectionReportGridView.setAdapter(inspectionReportAdapter);

		mallGoodsDetailModel = new MallGoodsDetailModel(this, new OnNetBackListener<MallGoodsDetailBean>() {
			@Override
			public void netBack(MallGoodsDetailBean data) {
				if (data == null) {
					Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {
						mallGoodsDetailBean = data;
						List<MallGoodsDetailBean.ResBean.GoodsAttrsBean> getGoods_attrs = mallGoodsDetailBean.getRes().getGoods_attrs();
						initMallDetailData(data);
					} else {
						Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		requestDetailsBean();
		if (ConstantClass.state == 1) {//如果已经登录检查是否收藏
			checkCollect();
		}

	}

	private void checkCollect() {
		CheckCollectSubmitBean checkCollectSubmitBean = new CheckCollectSubmitBean();
		checkCollectSubmitBean.setObjId(goodsId);
		checkCollectSubmitBean.setType("goods");

		new CheckCollectModel(this, new OnNetBackListener<CheckCollectBean>() {
			@Override
			public void netBack(CheckCollectBean data) {
				if (data == null) {
					Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {
						if ("1".equals(data.getRes().getStatus())) {//已经收藏
							isCollected = true;
							bt_mall_collect.setText("已收藏");
							collectId = data.getRes().getId();
						} else {
							isCollected = false;
							bt_mall_collect.setText("收藏");
						}
					} else {
						Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		}).request(JSONUtil.toJSON(checkCollectSubmitBean), true);
	}

	private void requestDetailsBean() {
		mallGoodsDetailModel.request("{\"goodsId\":\"" + goodsId + "\"}", true);
	}

	/**
	 * 将返回的数据填充到页面上
	 *
	 * @param data
	 */
	private void initMallDetailData(MallGoodsDetailBean data) {


		/*if (data.getRes().getIs_ported().equals("1")) {
			canSplitTv.setVisibility(View.VISIBLE);
		} else {
			canSplitTv.setVisibility(View.GONE);
		}
		//1仓单 2保证金 3信誉
		if ("1".equals(data.getRes().getPublish_type())) {
			releaseTypeTv.setBackgroundResource(R.drawable.shap_red);
		}
		if ("2".equals(data.getRes().getPublish_type())) {
			releaseTypeTv.setBackgroundResource(R.drawable.shap_orange);
		}
		if ("3".equals(data.getRes().getPublish_type())) {
			releaseTypeTv.setBackgroundResource(R.drawable.shap_orange);
		}
		releaseTypeTv.setText(data.getRes().getPublish_type_str());*/


		tvGoodsName.setText(data.getRes().getTitle());
		tvGoodsPrice.setText(data.getRes().getPrice());
		tvViewTimes.setText(data.getRes().getView_times());
		tvAddTime.setText(data.getRes().getAdd_time_format());

		tvPayMethod.setText(data.getRes().getPay_type_str());
		tvProductCode.setText(data.getRes().getProduct_code());
		tvIsPorted.setText(data.getRes().getIs_ported_str());
		tvDeliveryArea.setText(data.getRes().getDelivery_area());
		tvDeliveryType.setText(data.getRes().getDelivery_type_str());
		tvCatName.setText(data.getRes().getCat_name());

		tvNumber.setText(data.getRes().getNumber());
		tvNumberUnit.setText(data.getRes().getUnit());

		step_price = data.getRes().getStep_price();

		long endTime = Long.parseLong(TextUtils.isEmpty(data.getRes().getEnd_time()) ? "0" : data.getRes().getEnd_time());
		countDownLinearLayout.startCountDown(endTime);

		//产品指标
		List<MallGoodsDetailBean.ResBean.GoodsAttrsBean> getGoods_attrs = data.getRes().getGoods_attrs();
		productIndexBeanList.clear();
		if (getGoods_attrs != null && getGoods_attrs.size() > 0) {

			for (int i = 0; i < getGoods_attrs.size(); i++) {
			 //if (!("3".equals(getGoods_attrs.get(i).getAttr_type())) && !("5".equals(getGoods_attrs.get(i).getAttr_type()))) {
					ProductIndexBean productIndexBean = new ProductIndexBean();
					productIndexBean.setId(getGoods_attrs.get(i).getId());
					productIndexBean.setName(getGoods_attrs.get(i).getName());
					productIndexBean.setDefault_value(getGoods_attrs.get(i).getDefault_value());

					productIndexBeanList.add(productIndexBean);

				// }

			}
			ProductIndexListBeans productIndexListBeans = null;
			for (int i = 0; i < productIndexBeanList.size(); i++) {//构造符合条件的数据
				if (i == 0 || i % 2 == 0) {
					productIndexListBeans = new ProductIndexListBeans();
					productIndexListBeanses.add(productIndexListBeans);
				}
				productIndexListBeans.getBeans().add((productIndexBeanList.get(i)));
			}
		}
		productExtraInfAdapter.notifyDataSetChanged();
		//质检报告
		check_report.clear();
		if (data.getRes().getCheck_report_info() != null) {
			check_report.addAll(data.getRes().getCheck_report_info());
		}
		inspectionReportAdapter.notifyDataSetChanged();

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (ConstantClass.state == 1) {//如果已经登录检查是否收藏
			checkCollect();
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
			case R.id.title_left_img:
				finish();
				break;
			case R.id.order_btn:

				if (ConstantClass.state == 0) {
					intent.setClass(this, LoginActivity.class);
					startActivity(intent);
					return;
				} else {
					intent.setClass(MallDetailsActivity.this, MallOrderActivity.class);
					intent.putExtra("mallGoodsDetailBean", mallGoodsDetailBean);
					startActivity(intent);
				}
				break;
			case R.id.rl_step_price:
				showLadderPrice(step_price);
				break;
			case R.id.bt_mall_collect://收藏
				if (ConstantClass.state == 0) {
					intent.setClass(this, LoginActivity.class);
					startActivity(intent);
					return;
				} else {
					if (isCollected) {//已经收藏 取消收藏
						removeCollect();
					} else {//未收藏 去收藏
						addCollect("goods", mallGoodsDetailBean.getRes().getId());
					}
				}
				break;
			default:
				break;
		}
	}

	private void removeCollect() {//取消收藏
		CancelCollectSubmitBean cancelCollectSubmitBean = new CancelCollectSubmitBean();
		cancelCollectSubmitBean.setId(collectId);

		new CancelCollectModel(this, new OnNetBackListener<CancelCollectBean>() {
			@Override
			public void netBack(CancelCollectBean data) {
				if (data == null) {
					Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {//成功取消
						isCollected = false;
						bt_mall_collect.setText("收藏");
					} else {
						Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		}).request(JSONUtil.toJSON(cancelCollectSubmitBean), true);
	}

	private void addCollect(String type, String objId) {
		new AddCollectModel(this, new OnNetBackListener<AddCollectBean>() {
			@Override
			public void netBack(AddCollectBean data) {
				if (data == null) {
					Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {
						//Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
						checkCollect();
					} else {
						Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		}).request(JSONUtil.toJSON(new AddCollectSubmitBean(type, objId)), true);

	}

	@Override
	protected void onDestroy() {
		countDownLinearLayout.stopTimer();
		super.onDestroy();
	}
}
